home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / hplip / base / pkit.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-10-28  |  14KB  |  423 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import os.path as os
  6. import sys
  7. import re
  8. import time
  9. import cStringIO
  10. import ConfigParser
  11. import shutil
  12. import stat
  13. from base.logger import *
  14. from base.g import *
  15. from base.codes import *
  16. from base import utils, device
  17. import dbus
  18. import dbus.service as dbus
  19. import gobject
  20. import warnings
  21. warnings.simplefilter('ignore', DeprecationWarning)
  22.  
  23. class AccessDeniedException(dbus.DBusException):
  24.     _dbus_error_name = 'com.hp.hplip.AccessDeniedException'
  25.  
  26.  
  27. class UnsupportedException(dbus.DBusException):
  28.     _dbus_error_name = 'com.hp.hplip.UnsupportedException'
  29.  
  30.  
  31. class UsageError(dbus.DBusException):
  32.     _dbus_error_name = 'com.hp.hplip.UsageError'
  33.  
  34. POLICY_KIT_ACTION = 'com.hp.hplip'
  35. INSTALL_PLUGIN_ACTION = 'com.hp.hplip.installplugin'
  36.  
  37. def get_service_bus():
  38.     return dbus.SystemBus()
  39.  
  40.  
  41. def get_service(bus = None):
  42.     if not bus:
  43.         bus = get_service_bus()
  44.     
  45.     service = bus.get_object(BackendService.SERVICE_NAME, '/')
  46.     service = dbus.Interface(service, BackendService.INTERFACE_NAME)
  47.     return service
  48.  
  49.  
  50. class PolicyKitAuthentication(object):
  51.     
  52.     def __init__(self):
  53.         super(PolicyKitAuthentication, self).__init__()
  54.         self.pkit = None
  55.         self.auth = None
  56.  
  57.     
  58.     def is_authorized(self, action_id, pid = None):
  59.         if pid == None:
  60.             pid = os.getpid()
  61.         
  62.         pid = dbus.UInt32(pid)
  63.         authorized = self.policy_kit.IsProcessAuthorized(action_id, pid, False)
  64.         log.debug('is_authorized(%s) = %r' % (action_id, authorized))
  65.         return authorized == 'yes'
  66.  
  67.     
  68.     def obtain_authorization(self, action_id, widget = None):
  69.         xid = self.is_authorized(action_id) if self.is_authorized(action_id) else 0
  70.         xid = dbus.UInt32(xid)
  71.         pid = dbus.UInt32(os.getpid())
  72.         granted = self.auth_agent.ObtainAuthorization(action_id, xid, pid)
  73.         log.debug('obtain_authorization(%s) = %r' % (action_id, granted))
  74.         return bool(granted)
  75.  
  76.     
  77.     def get_policy_kit(self):
  78.         if self.pkit:
  79.             return self.pkit
  80.         service = dbus.SystemBus().get_object('org.freedesktop.PolicyKit', '/')
  81.         self.pkit = dbus.Interface(service, 'org.freedesktop.PolicyKit')
  82.         return self.pkit
  83.  
  84.     policy_kit = property(get_policy_kit)
  85.     
  86.     def get_auth_agent(self):
  87.         if self.auth:
  88.             return self.auth
  89.         self.auth = dbus.SessionBus().get_object('org.freedesktop.PolicyKit.AuthenticationAgent', '/')
  90.         return self.auth
  91.  
  92.     auth_agent = property(get_auth_agent)
  93.  
  94.  
  95. class PolicyKitService(dbus.service.Object):
  96.     
  97.     def check_permission_v0(self, sender, action = POLICY_KIT_ACTION):
  98.         if not sender:
  99.             log.error('Session not authorized by PolicyKit')
  100.             raise AccessDeniedException('Session not authorized by PolicyKit')
  101.         sender
  102.         
  103.         try:
  104.             policy_auth = PolicyKitAuthentication()
  105.             bus = dbus.SystemBus()
  106.             dbus_object = bus.get_object('org.freedesktop.DBus', '/')
  107.             dbus_object = dbus.Interface(dbus_object, 'org.freedesktop.DBus')
  108.             pid = dbus.UInt32(dbus_object.GetConnectionUnixProcessID(sender))
  109.             granted = policy_auth.is_authorized(action, pid)
  110.             if not granted:
  111.                 log.error('Process not authorized by PolicyKit')
  112.                 raise AccessDeniedException('Process not authorized by PolicyKit')
  113.             granted
  114.             granted = policy_auth.policy_kit.IsSystemBusNameAuthorized(action, sender, False)
  115.             if granted != 'yes':
  116.                 log.error('Session not authorized by PolicyKit version 0')
  117.                 raise AccessDeniedException('Session not authorized by PolicyKit')
  118.             granted != 'yes'
  119.         except AccessDeniedException:
  120.             log.warning('AccessDeniedException')
  121.             raise 
  122.         except dbus.DBusException:
  123.             ex = None
  124.             log.warning('AccessDeniedException %r', ex)
  125.             raise AccessDeniedException(ex.message)
  126.  
  127.  
  128.     
  129.     def check_permission_v1(self, sender, connection, action = POLICY_KIT_ACTION):
  130.         if not sender or not connection:
  131.             log.error('Session not authorized by PolicyKit')
  132.             raise AccessDeniedException('Session not authorized by PolicyKit')
  133.         not connection
  134.         system_bus = dbus.SystemBus()
  135.         obj = system_bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority', 'org.freedesktop.PolicyKit1.Authority')
  136.         policy_kit = dbus.Interface(obj, 'org.freedesktop.PolicyKit1.Authority')
  137.         info = dbus.Interface(connection.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus/Bus', False), 'org.freedesktop.DBus')
  138.         pid = info.GetConnectionUnixProcessID(sender)
  139.         subject = ('unix-process', {
  140.             'pid': dbus.UInt32(pid, variant_level = 1) })
  141.         details = {
  142.             '': '' }
  143.         flags = dbus.UInt32(1)
  144.         cancel_id = ''
  145.         (ok, notused, details) = policy_kit.CheckAuthorization(subject, action, details, flags, cancel_id)
  146.         if not ok:
  147.             log.error('Session not authorized by PolicyKit version 1')
  148.         
  149.         return ok
  150.  
  151.  
  152.  
  153. class BackendService(PolicyKitService):
  154.     INTERFACE_NAME = 'com.hp.hplip'
  155.     SERVICE_NAME = 'com.hp.hplip'
  156.     LOGFILE_NAME = '/tmp/hp-pkservice.log'
  157.     
  158.     def __init__(self, connection = None, path = '/', logfile = LOGFILE_NAME):
  159.         if connection is None:
  160.             connection = get_service_bus()
  161.         
  162.         super(BackendService, self).__init__(connection, path)
  163.         self.name = dbus.service.BusName(self.SERVICE_NAME, connection)
  164.         self.loop = gobject.MainLoop()
  165.         self.version = 0
  166.         log.set_logfile('%s.%d' % (logfile, os.getpid()))
  167.         log.set_level('debug')
  168.  
  169.     
  170.     def run(self, version = None):
  171.         if version is None:
  172.             version = policykit_version()
  173.             if version is None:
  174.                 log.error('Unable to determine installed PolicyKit version')
  175.                 return None
  176.         
  177.         self.version = version
  178.         log.set_where(Logger.LOG_TO_CONSOLE_AND_FILE)
  179.         log.debug('Starting back-end service loop (version %d)' % version)
  180.         self.loop.run()
  181.  
  182.     
  183.     def installPlugin(self, src_dir, sender = None, connection = None):
  184.         if self.version == 0:
  185.             
  186.             try:
  187.                 self.check_permission_v0(sender, INSTALL_PLUGIN_ACTION)
  188.             except AccessDeniedException:
  189.                 e = None
  190.                 return False
  191.             
  192.  
  193.         None<EXCEPTION MATCH>AccessDeniedException
  194.         if self.version == 1:
  195.             if not self.check_permission_v1(sender, connection, INSTALL_PLUGIN_ACTION):
  196.                 return False
  197.         else:
  198.             log.error('installPlugin: invalid PolicyKit version %d' % self.version)
  199.             return False
  200.         self.check_permission_v1(sender, connection, INSTALL_PLUGIN_ACTION).debug("installPlugin: installing from '%s'" % src_dir)
  201.         if not copyPluginFiles(src_dir):
  202.             log.error('Plugin installation failed')
  203.             return False
  204.         return True
  205.  
  206.     installPlugin = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = 's', out_signature = 'b', sender_keyword = 'sender', connection_keyword = 'connection')(installPlugin)
  207.     
  208.     def shutdown(self, sender = None, connection = None):
  209.         log.debug('Stopping backend service')
  210.         self.loop.quit()
  211.         return True
  212.  
  213.     shutdown = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = '', out_signature = 'b', sender_keyword = 'sender', connection_keyword = 'connection')(shutdown)
  214.  
  215.  
  216. class PolicyKit(object):
  217.     
  218.     def __init__(self, version = None):
  219.         if version is None:
  220.             version = policykit_version()
  221.             if version is None:
  222.                 log.error('Unable to determine installed PolicyKit version')
  223.                 return None
  224.         
  225.         self.bus = dbus.SystemBus()
  226.         self.obj = self.bus.get_object(POLICY_KIT_ACTION, '/')
  227.         self.iface = dbus.Interface(self.obj, dbus_interface = POLICY_KIT_ACTION)
  228.         self.version = version
  229.  
  230.     
  231.     def installPlugin(self, src_dir):
  232.         if self.version == 0:
  233.             auth = PolicyKitAuthentication()
  234.             if not auth.is_authorized(INSTALL_PLUGIN_ACTION):
  235.                 if not auth.obtain_authorization(INSTALL_PLUGIN_ACTION):
  236.                     return None
  237.             
  238.         
  239.         
  240.         try:
  241.             ok = self.iface.installPlugin(src_dir)
  242.             return ok
  243.         except dbus.DBusException:
  244.             e = None
  245.             log.debug('installPlugin: %s' % str(e))
  246.             return False
  247.  
  248.  
  249.     
  250.     def shutdown(self):
  251.         if self.version == 0:
  252.             auth = PolicyKitAuthentication()
  253.             if not auth.is_authorized(INSTALL_PLUGIN_ACTION):
  254.                 if not auth.obtain_authorization(INSTALL_PLUGIN_ACTION):
  255.                     return None
  256.             
  257.         
  258.         
  259.         try:
  260.             ok = self.iface.shutdown()
  261.             return ok
  262.         except dbus.DBusException:
  263.             e = None
  264.             log.debug('shutdown: %s' % str(e))
  265.             return False
  266.  
  267.  
  268.  
  269.  
  270. def copyPluginFiles(src_dir):
  271.     os.chdir(src_dir)
  272.     plugin_spec = ConfigBase('plugin.spec')
  273.     products = plugin_spec.keys('products')
  274.     BITNESS = utils.getBitness()
  275.     ENDIAN = utils.getEndian()
  276.     PPDDIR = sys_conf.get('dirs', 'ppd')
  277.     DRVDIR = sys_conf.get('dirs', 'drv')
  278.     HOMEDIR = sys_conf.get('dirs', 'home')
  279.     DOCDIR = sys_conf.get('dirs', 'doc')
  280.     CUPSBACKENDDIR = sys_conf.get('dirs', 'cupsbackend')
  281.     CUPSFILTERDIR = sys_conf.get('dirs', 'cupsfilter')
  282.     RULESDIR = '/etc/udev/rules.d'
  283.     processor = utils.getProcessor()
  284.     if processor == 'power_machintosh':
  285.         ARCH = 'ppc'
  286.     else:
  287.         ARCH = 'x86_%d' % BITNESS
  288.     if BITNESS == 64:
  289.         SANELIBDIR = '/usr/lib64/sane'
  290.         LIBDIR = '/usr/lib64'
  291.     else:
  292.         SANELIBDIR = '/usr/lib/sane'
  293.         LIBDIR = '/usr/lib'
  294.     copies = []
  295.     for PRODUCT in products:
  296.         MODEL = PRODUCT.replace('hp-', '').replace('hp_', '')
  297.         for s in plugin_spec.get('products', PRODUCT).split(','):
  298.             if not plugin_spec.has_section(s):
  299.                 log.error('Missing section [%s]' % s)
  300.                 return False
  301.             src = plugin_spec.get(s, 'src', '')
  302.             trg = plugin_spec.get(s, 'trg', '')
  303.             link = plugin_spec.get(s, 'link', '')
  304.             if not src:
  305.                 log.error("Missing 'src=' value in section [%s]" % s)
  306.                 return False
  307.             if not trg:
  308.                 log.error("Missing 'trg=' value in section [%s]" % s)
  309.                 return False
  310.             src = os.path.basename(utils.cat(src))
  311.             trg = utils.cat(trg)
  312.             copies.append((src, trg, link))
  313.         
  314.     
  315.     copies = utils.uniqueList(copies)
  316.     copies.sort()
  317.     os.umask(0)
  318.     for src, trg, link in copies:
  319.         if not os.path.exists(src):
  320.             log.debug('Source file %s does not exist. Skipping.' % src)
  321.             continue
  322.         
  323.         if os.path.exists(trg):
  324.             log.debug('Target file %s already exists. Replacing.' % trg)
  325.             os.remove(trg)
  326.         
  327.         trg_dir = os.path.dirname(trg)
  328.         if not os.path.exists(trg_dir):
  329.             log.debug('Target directory %s does not exist. Creating.' % trg_dir)
  330.             os.makedirs(trg_dir, 493)
  331.         
  332.         if not os.path.isdir(trg_dir):
  333.             log.error('Target directory %s exists but is not a directory. Skipping.' % trg_dir)
  334.             continue
  335.         
  336.         
  337.         try:
  338.             shutil.copyfile(src, trg)
  339.         except (IOError, OSError):
  340.             e = None
  341.             log.error('File copy failed: %s' % e.strerror)
  342.             continue
  343.             continue
  344.  
  345.         if not os.path.exists(trg):
  346.             log.error('Target file %s does not exist. File copy failed.' % trg)
  347.             continue
  348.         else:
  349.             os.chmod(trg, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH)
  350.         if link:
  351.             if os.path.exists(link):
  352.                 log.debug('Symlink already exists. Replacing.')
  353.                 os.remove(link)
  354.             
  355.             log.debug('Creating symlink %s (link) to file %s (target)...' % (link, trg))
  356.             
  357.             try:
  358.                 os.symlink(trg, link)
  359.             except (OSError, IOError):
  360.                 e = None
  361.                 log.debug('Unable to create symlink: %s' % e.strerror)
  362.             except:
  363.                 None<EXCEPTION MATCH>(OSError, IOError)
  364.             
  365.  
  366.         None<EXCEPTION MATCH>(OSError, IOError)
  367.     
  368.     log.debug('Updating hplip.conf - installed = 1')
  369.     sys_state.set('plugin', 'installed', '1')
  370.     log.debug('Updating hplip.conf - eula = 1')
  371.     sys_state.set('plugin', 'eula', '1')
  372.     return True
  373.  
  374.  
  375. def run_plugin_command(required = True, plugin_reason = PLUGIN_REASON_NONE):
  376.     su_sudo = None
  377.     need_sudo = True
  378.     if utils.to_bool(sys_conf.get('configure', 'policy-kit')):
  379.         
  380.         try:
  381.             obj = PolicyKit()
  382.             su_sudo = '%s'
  383.             need_sudo = False
  384.             log.debug('Using PolicyKit for authentication')
  385.         except dbus.DBusException:
  386.             ex = None
  387.             log.error('PolicyKit NOT installed when configured for use')
  388.         except:
  389.             None<EXCEPTION MATCH>dbus.DBusException
  390.         
  391.  
  392.     None<EXCEPTION MATCH>dbus.DBusException
  393.     if os.geteuid() == 0:
  394.         su_sudo = '%s'
  395.         need_sudo = False
  396.     
  397.     if need_sudo:
  398.         su_sudo = utils.su_sudo()
  399.         if su_sudo is None:
  400.             log.error("Unable to find a suitable sudo command to run 'hp-plugin'")
  401.             return (False, False)
  402.     
  403.     req = '--required'
  404.     if not required:
  405.         req = '--optional'
  406.     
  407.     if utils.which('hp-plugin'):
  408.         cmd = su_sudo % 'hp-plugin -u %s --reason %s' % (req, plugin_reason)
  409.     else:
  410.         cmd = su_sudo % 'python ./plugin.py -u %s --reason %s' % (req, plugin_reason)
  411.     log.debug('%s' % cmd)
  412.     (status, output) = utils.run(cmd, log_output = True, password_func = None, timeout = 1)
  413.     return (status == 0, True)
  414.  
  415.  
  416. def policykit_version():
  417.     if os.path.isdir('/usr/share/polkit-1'):
  418.         return 1
  419.     if os.path.isdir('/usr/share/PolicyKit'):
  420.         return 0
  421.     return None
  422.  
  423.